﻿import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { FormattedMessage } from 'react-intl';
import { List, InputItem, WhiteSpace, WingBlank, Button,Checkbox,Picker,Flex,Modal,Badge } from 'antd-mobile';
import { createForm } from 'rc-form';


const ListItem = List.Item;
const alert = Modal.alert;




class App extends React.Component { 
	constructor(props) {
		super(props);

		const Lang = window.LangMessage ||{};

		this.state={
			errorMap:{},
			isCertificated:false,
			userInfo:{},
			listMap:{
				cardType : [{label:Lang.ID_card ||"身份证",value:"1"},{label:Lang.passport || "护照",value:"2"}]
			}
		}

		this.keyCodes = [{
			keycode:"name",
			text:Lang.name || "姓名",
		    disabled:true
		},{
			keycode:"certiType",
			text:Lang.certi_type || "证件类型",
		    disabled:true
		},{
			keycode:"certiNo",
			text:Lang.certi_no || "证件号码",
		    disabled:true
		},{
			keycode:"gender",
			text:Lang.gender_text || "性别",
		    disabled:true
		},{
			keycode:"birthday",
			text:Lang.date_of_birth || "出生日期",
		    disabled:true
		}];

		this.otherKeyCodes = [{
			keycode:"address",
			text:Lang.address_detail || "详细地址"
		},{
			keycode:"phone",
			text:Lang.phone_no || "手机号码"
		},{
			keycode:"email",
			text:Lang.email || "电子邮箱"
		}];

		this.sexMap={
			FMALE:Lang.female || "女",
			MALE:Lang.male || "男"
		}
		
		this.cardTypeMap={
			SHENFENZHENG:Lang.ID_card || "身份证",
			HUZHAO:Lang.passport || "护照",
			HUKOUBU:Lang.residence_booklet || "户口簿",
			JUNGUANZHENG: Lang.military_identity_card || "军人身份证",
			POLICYID: Lang.armed_police_identity_card || "武装警察身份证",
			GAJMLAIWANGCERTI: Lang.HK_Macao_to_mainland || "港澳居民来往内地通行证",
			TAIBAOCERTI: Lang.TW_to_mainland || "台湾居民来往内地通行证",
			WAIGUORENCERTI: Lang.foreigner_mainland || "外国人永久居留身份证"
		}

	} 

	componentDidMount(){
		this.requestUserInfo();		
	}

	requestUserInfo=()=>{
		let data = {
			"id": 65110,
			"targetCustomerId": 123234,
			"personId": 654654,
			"certiNo": "23453476468745673547",
			"certiType": "SHENFENZHENG",
			"name" : "aa",
			"birthday" : "1995-05-05 00:00:00",
			"gender" : "MALE",
			"phone": "13828727663",
			"address": "南山区三诺智慧大厦",
			"email" : "1342@qq.com",
			"provinceCode" : "1234",
			"provinceName" : "黑龙江省",
			"cityCode" : "21341",
			"cityName" : "哈尔滨市"
		}

		//this.setState({userInfo:data,isCertificated:!!data.name});

		//return;
		T.fetch({				
			url:"/customer/detail.json"
			
		}).then((res)=>{
			if(res.success){
				let data = res.value ||{};
				let otherData = {};

				if(data.gender){
					data.gender = this.sexMap[data.gender] ||data.gender;
				}
				if(data.certiType){
					data.certiType = this.cardTypeMap[data.certiType] ||data.certiType;
				}
				if(data.birthday){
					data.birthday = data.birthday.substr(0,10);
				}
				if(data.phone){
					otherData.phone = data.phone;
					data.phone = data.phone.phoneNo;					
				}
				if(data.email){
					otherData.email = data.email;
					data.email = data.email.email;					
				}
				if(data.address){
					otherData.address = data.address;
					data.address = data.address.addressDetail;					
				}
				this.setState({otherData:otherData,userInfo:data,isCertificated:!!data.name});
			}
		});
		T.fetch({				
			url:"/customer/password/transaction/hasModified.json",
			noTip:true						
		}).then((res)=>{
			if(res.success){								
				this.setState({hasPassword:true});
			}else{
				this.setState({hasPassword:false});
			}
		});


	}

	requestPlace = ()=>{
		T.fetch({				
			url:"/tools/city/list.json",
			data:{
				"parentCode": "0"
			}
		}).then((res)=>{
			if(res.success){
				let data = res.value ||{};
				data = data.map((item)=>{
					return {
						label:item.name,
						value:item.code
					}
				})

				let listMap = this.state.listMap;
				listMap.place = data;
				this.setState({
					listMap
				})
			}
		});	

	}
	
	onErrorClick=(keyCode)=>{
		const {getFieldError } = this.props.form;
		let msg = getFieldError(keyCode);
		if(msg){
			T.showError(msg.join(","),2);
		}	
	}
	
	submitAction=()=>{
		this.props.form.validateFields((error, values) => {
			var errorMap ={}
			if(error){
				for(var key in error){
					errorMap[key] = 1;
				}
			}else{				
				if(values.phone){
					values.phone = T.trimAll(values.phone);
				}
				let otherData = this.state.otherData;
				var data ={
					"phoneDetails": [],
					"emailDetails": [],
					"addressDetails": []
				};
				if(this.state.otherData){
					data.phoneDetails.push(otherData.phone || {});
					data.emailDetails.push(otherData.email || {});
					data.addressDetails.push(otherData.address || {});
				}else{
					data ={
						"phoneDetails":[{phoneNo:''}],
						"emailDetails": [{emailDetail:''}],
						"addressDetails": [{addressDetail:''}]
					};	
				}				
				data.emailDetails[0].emailDetail = values.email;
				data.phoneDetails[0].phoneNo = values.phone;				
				data.addressDetails[0].addressDetail = values.address;			
				T.fetch({				
					url:"/customer/update.json",
					data:data
					}).then((res)=>{
						if(res.success){
							actions.routing.push('info-main');
						}
					});	
			}
			this.setState({
				errorMap
			});
			console.log(error, values);
		});
	}

	getItemDom = (item,index)=>{
		const Lang = window.LangMessage ||{};
		const { getFieldProps } = this.props.form;
		const userInfo = this.state.userInfo;
		let dom;
		const listMap = this.state.listMap;
		let keyCode = item.keycode;
		switch(item.type){
			
			case "select" :
				dom = <Picker data={listMap[keyCode]} cols={1}  key={index}
						{...getFieldProps(keyCode,{
							//initialValue:"1",
							rules: [{
								required: item.required === undefined ? true:item.required,
								message:item.message || ((Lang.please_select || "请选择") + item.text),
								pattern:item.pattern
							}]
						})}
					>
						<ListItem arrow="horizontal">{item.text}</ListItem>
					</Picker>;
			break;
			default:
				dom = <InputItem  key={index}
				{...getFieldProps(keyCode,{
					initialValue:userInfo[item.keycode],
					rules: [{
						required: item.required === undefined ? true:item.required,
						message:item.message || ((Lang.text_input ||"请输入") + item.text),
						pattern:item.pattern
					}]
				})}
				disabled={!!item.disabled}
				type={item.type}
				error ={this.state.errorMap[keyCode]}
				onErrorClick={this.onErrorClick.bind(this,keyCode)}
				clear
				placeholder={(Lang.text_input ||"请输入") + item.text}
				>{item.text}</InputItem>
		}

		return dom;
	}

	toCertificate = ()=>{
		const Lang = window.LangMessage ||{};
		if(!this.state.hasPassword){
			// alert('实名认证之前需要设置交易密码', '', [
			// 	{ text: '取消'},
			// 	{ text: '去设置', onPress: () => {
			// 		actions.routing.push({
			// 			pathname: '/password-set',
			// 			search: '?backurl='+encodeURIComponent(location.href)
			// 		})
			// 	} },
			//   ])
			var r=confirm(Lang.set_pwd__before_tip || "实名认证之前需要设置交易密码");
			if (r==true)
			{
				actions.routing.push({
					pathname: '/password-set',
					search: '?backurl='+encodeURIComponent(location.href)
				})
			}						
			return;
		}
		location.href= "info-certificate";
	}
	
	render() {
		const Lang = window.LangMessage ||{};
		let words = this.state.isCertificated ?Lang.cer_again || "再次认证":Lang.to_cert || "去认证";
		return (<div className="info-base">
			<WhiteSpace/>
			<List className="certi-div">
					<Button className="diy_color pr20" onClick={this.toCertificate}>{words}</Button>
			</List>

			{this.state.isCertificated &&
				<List>
					{this.keyCodes.map((item,index)=>
						this.getItemDom(item,index)
					)}
					
				</List>
			}
			
			
			<List className="mt10">
				{this.otherKeyCodes.map((item,index)=>
					this.getItemDom(item,index)
				)}
				
			</List>

		<div className="whiteSpace"></div>
			<div className="footer clearfix">
				<Flex>
					<Flex.Item className="tac pt30 pb30 fcw f28 diy_background" onClick={this.submitAction}><FormattedMessage id='save' defaultMessage='保存'/></Flex.Item>
				</Flex>
			</div>
	  	</div>)
	}
}

const AppForm = createForm()(App);

export default AppForm;